//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 1995-2000, The Hypersonic SQL Group.
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the Hypersonic SQL Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * on behalf of the Hypersonic SQL Group.
 *
 *
 * For work added by the HSQL Development Group:
 *
 * Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.Text;

namespace EffiProzDB
{
    /**
     * Reusable object for processing LIKE queries.
     *
     * Enhanced _in successive versions of HSQLDB.
     *
     * @author Thomas Mueller (Hypersonic SQL Group)
     * @version 1.8.0
     * @since Hypersonic SQL
     */

    // boucherb@users 20030930 - patch 1.7.2 - optimize into joins if possible
    // fredt@users 20031006 - patch 1.7.2 - reuse Like objects for all rows
    public class Like
    {

        private char[] cLike;
        private int[] wildCardType;
        private int iLen;
        private bool isIgnoreCase;
        private int iFirstWildCard;
        private bool isNull;
        public char? escapeChar;
        public bool hasCollation;
        public bool optimised;
        public  const int UNDERSCORE_CHAR = 1;
        public  const int PERCENT_CHAR = 2;

        public Like(char escape, bool collation)
        {
            escapeChar = escape;
            hasCollation = collation;
        }

        /**
         * param setter
         *
         * @param s
         * @param ignorecase
         */
        public void setParams(Session session, string s, bool ignorecase)
        {

            isIgnoreCase = ignorecase;

            normalize(session, s);

            optimised = true;
        }

        /**
         * Resets the search pattern;
         */
        public void resetPattern(Session session, string s)
        {
            normalize(session, s);
        }

        private string getStartsWith()
        {

            if (iLen == 0)
            {
                return "";
            }

            StringBuilder s = new StringBuilder();
            int i = 0;

            for (; (i < iLen) && (wildCardType[i] == 0); i++)
            {
                s.Append(cLike[i]);
            }

            if (i == 0)
            {
                return null;
            }

            return s.ToString();
        }

        /**
         * Method declaration
         *
         *
         * @param o
         *
         * @return
         */
        public bool compare(Session session, string s)
        {

            if (s == null)
            {
                return false;
            }

            if (isIgnoreCase)
            {
                s = session.database.collation.toUpperCase(s);
            }

            return compareAt(s, 0, 0, s.Length) ? true
                                                  : false;
        }

        /**
         * Method declaration
         *
         *
         * @param s
         * @param i
         * @param j
         * @param jLen
         *
         * @return
         */
        private bool compareAt(string s, int i, int j, int jLen)
        {

            for (; i < iLen; i++)
            {
                switch (wildCardType[i])
                {

                    case 0:                  // general character
                        if ((j >= jLen) || (cLike[i] != s[(j++)]))
                        {
                            return false;
                        }
                        break;

                    case UNDERSCORE_CHAR:    // underscore: do not test this character
                        if (j++ >= jLen)
                        {
                            return false;
                        }
                        break;

                    case PERCENT_CHAR:       // percent: none or any character(s)
                        if (++i >= iLen)
                        {
                            return true;
                        }

                        while (j < jLen)
                        {
                            if ((cLike[i] == s[(j)])
                                    && compareAt(s, i, j, jLen))
                            {
                                return true;
                            }

                            j++;
                        }

                        return false;
                }
            }

            if (j != jLen)
            {
                return false;
            }

            return true;
        }

        /**
         * Method declaration
         *
         *
         * @param pattern
         * @param b
         */
        private void normalize(Session session, string pattern) {

        isNull = pattern == null;

        if (!isNull && isIgnoreCase) {
            pattern = session.database.collation.toUpperCase(pattern);
        }

        iLen           = 0;
        iFirstWildCard = -1;

        int l = pattern == null ? 0
                                : pattern.Length ;

        cLike        = new char[l];
        wildCardType = new int[l];

        bool bEscaping = false,
                bPercent  = false;

        for (int i = 0; i < l; i++) {
            char c = pattern[i];

            if (bEscaping == false) {
                if (escapeChar != null && escapeChar == c) {
                    bEscaping = true;

                    continue;
                } else if (c == '_') {
                    wildCardType[iLen] = UNDERSCORE_CHAR;

                    if (iFirstWildCard == -1) {
                        iFirstWildCard = iLen;
                    }
                } else if (c == '%') {
                    if (bPercent) {
                        continue;
                    }

                    bPercent           = true;
                    wildCardType[iLen] = PERCENT_CHAR;

                    if (iFirstWildCard == -1) {
                        iFirstWildCard = iLen;
                    }
                } else {
                    bPercent = false;
                }
            } else {
                bPercent  = false;
                bEscaping = false;
            }

            cLike[iLen++] = c;
        }

        for (int i = 0; i < iLen - 1; i++) {
            if ((wildCardType[i] == PERCENT_CHAR)
                    && (wildCardType[i + 1] == UNDERSCORE_CHAR)) {
                wildCardType[i]     = UNDERSCORE_CHAR;
                wildCardType[i + 1] = PERCENT_CHAR;
            }
        }
    }

        public bool hasWildcards()
        {
            return iFirstWildCard != -1;
        }

        public bool isEquivalentToFalsePredicate()
        {
            return isNull;
        }

        public bool isEquivalentToEqualsPredicate()
        {
            return iFirstWildCard == -1;
        }

        public bool isEquivalentToNotNullPredicate()
        {

            if (isNull || !hasWildcards())
            {
                return false;
            }

            for (int i = 0; i < wildCardType.Length; i++)
            {
                if (wildCardType[i] != PERCENT_CHAR)
                {
                    return false;
                }
            }

            return true;
        }

        public bool isEquivalentToBetweenPredicate()
        {

            return iFirstWildCard > 0
                   && iFirstWildCard == wildCardType.Length - 1
                   && cLike[iFirstWildCard] == '%';
        }

        public bool isEquivalentToBetweenPredicateAugmentedWithLike()
        {
            return iFirstWildCard > 0 && cLike[iFirstWildCard] == '%';
        }

        public string getRangeLow()
        {
            return getStartsWith();
        }

        public string getRangeHigh()
        {

            string s = getStartsWith();

            return s == null ? null
                             : s + "\uffff";
        }

        public string describe(Session session)
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(base.ToString()).Append("[\n");
            sb.Append("escapeChar=").Append(escapeChar).Append('\n');
            sb.Append("isNull=").Append(isNull).Append('\n');
            sb.Append("optimised=").Append(optimised).Append('\n');
            sb.Append("isIgnoreCase=").Append(isIgnoreCase).Append('\n');
            sb.Append("iLen=").Append(iLen).Append('\n');
            sb.Append("iFirstWildCard=").Append(iFirstWildCard).Append('\n');
            sb.Append("cLike=");
            sb.Append(cLike.ToString());
            sb.Append('\n');
            sb.Append("wildCardType=");
            sb.Append(wildCardType.ToString());
            sb.Append(']');

            return sb.ToString();
        }
    }
}
